package rexsee.security;

import java.util.zip.Adler32;
import java.util.zip.CRC32;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import rexsee.core.utilities.Utilities;

public class RexseeCheckSum implements JavascriptInterface {

	public static final String INTERFACE_NAME = "CheckSum";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseeCheckSum(childBrowser);
	}

	private final Browser mBrowser;

	public RexseeCheckSum(Browser browser) {
		mBrowser = browser;
	}

	//JavaScript Interface
	public long adler32(String data) {
		return adler32(data, false);
	}
	public long adler32(String data, boolean isFile) {
		byte[] bytes = (isFile) ? Utilities.getContent(data) : data.getBytes();
		if (bytes == null) {
			mBrowser.exception(getInterfaceName(), "Error on reading data.");
			return -1;
		}
		Adler32 adler32 = new Adler32();
		adler32.update(bytes);
		return adler32.getValue();
	}
	public long crc32(String data) {
		return crc32(data, false);
	}
	public long crc32(String data, boolean isFile) {
		byte[] bytes = (isFile) ? Utilities.getContent(data) : data.getBytes();
		if (bytes == null) {
			mBrowser.exception(getInterfaceName(), "Error on reading data.");
			return -1;
		}
		CRC32 crc32 = new CRC32();
		crc32.update(bytes);
		return crc32.getValue();
	}

}
